package com.ysten.basic.common.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * http协议请求工具类
 * 
 * @author Martin
 * 
 */
public class HttpReqUtils
{
    /**
     * 请求超时时间（秒） 
     */
    public static final int CONNECTION_TIME_OUT = 10;
    /**
     * 返回数据超时时间（秒）
     */
    public static final int RESPONSE_TIME_OUT = 10;

    /**
     * 下载文件的缓存大小
     */
    public static final int  DOWNLOAD_BUF_SIZE= 2048;
    private static Logger logger = LoggerFactory.getLogger(HttpReqUtils.class);
    
    public static String doGet(String url)
    {
        HttpClient httpClient = null;
        httpClient = new DefaultHttpClient();
        //设置超时时间
        HttpConnectionParams.setConnectionTimeout(httpClient.getParams(),1000 * CONNECTION_TIME_OUT);
        HttpConnectionParams.setSoTimeout(httpClient.getParams(),1000 * RESPONSE_TIME_OUT);

        HttpEntity entity = null;
        HttpGet httpGet = new HttpGet(url);
        try
        {
            HttpResponse remoteResponse = httpClient.execute(httpGet);
            entity = remoteResponse.getEntity();
            return EntityUtils.toString(entity);
        }
        catch (Exception e)
        {
            logger.error("fetch remote content" + url + "  error", e);
            httpGet.abort();
        }
        return null;
    }
    
    public static String doPost(String url)
    {
        HttpClient httpClient = null;
        httpClient = new DefaultHttpClient();
        HttpConnectionParams.setConnectionTimeout(httpClient.getParams(),1000 * CONNECTION_TIME_OUT);
        HttpConnectionParams.setSoTimeout(httpClient.getParams(),1000 * RESPONSE_TIME_OUT);


        // 获取内容
        HttpEntity entity = null;
        HttpPost httpPost = new HttpPost(url);
        try
        {
            HttpResponse remoteResponse = httpClient.execute(httpPost);
            entity = remoteResponse.getEntity();
            return EntityUtils.toString(entity);
        }
        catch (Exception e)
        {
            logger.error("fetch remote content" + url + "  error", e);
            httpPost.abort();
        }
        return null;
    }
    
    public static File downLoad(String downUrl,String localUrl)
    {
    	 HttpClient httpClient = null;
         httpClient = new DefaultHttpClient();
         HttpConnectionParams.setConnectionTimeout(httpClient.getParams(),1000 * CONNECTION_TIME_OUT);
         HttpConnectionParams.setSoTimeout(httpClient.getParams(),1000 * RESPONSE_TIME_OUT);

         HttpGet httpGet = new HttpGet(downUrl);
         File localFile = null;
         try {
			HttpResponse httpResponse = httpClient.execute(httpGet);
			StatusLine statusLine = httpResponse.getStatusLine();
			if(statusLine.getStatusCode() == 200){
				localFile = new File(localUrl);
				FileOutputStream out = new FileOutputStream(localFile);
				InputStream in = httpResponse.getEntity().getContent();
				byte[] buf = new byte[DOWNLOAD_BUF_SIZE];
				int length = 0;
				while((length = in.read(buf)) != -1){
					out.write(buf, 0, length);
				}
				out.flush();
				out.close();
			}
		} catch (Exception e) {
			logger.error("http down load file  throw an error:{}", e);
		} 
         return localFile;
    }
}
